import axios from 'axios'

// API配置 - 读写分离架构
const API_CONFIG = {
  READ_API: import.meta.env.VITE_SHEEP_BREEDING_READ_API || 'http://39.96.200.62:8411', // 读API
  WRITE_API: import.meta.env.VITE_SHEEP_BREEDING_WRITE_API || 'http://39.96.200.62:8511', // 写API
  ENDPOINTS: {
    QUERY: '/api/EweLambing/query',
    CREATE: '/api/EweLambing/create',
    DETAIL: '/api/EweLambing',
    ALL: '/api/EweLambing/all'
  }
}

// 读API实例 - 用于查询操作
const readApi = axios.create({
  baseURL: API_CONFIG.READ_API,
  timeout: 10000
})

// 写API实例 - 用于新增、修改、删除操作
const writeApi = axios.create({
  baseURL: API_CONFIG.WRITE_API,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 为API实例添加Token
readApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

writeApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  console.log('发送请求:', config.url, config.data)
  return config
}, error => {
  console.error('请求拦截器错误:', error)
  return Promise.reject(error)
})

// 添加响应拦截器
writeApi.interceptors.response.use(response => {
  console.log('响应成功:', response.data)
  return response
}, error => {
  console.error('响应错误:', error.response?.data)
  return Promise.reject(error)
})

// 查询种母分娩列表（带条件）
export function getEweLambingList(params: any) {
  return readApi.post(API_CONFIG.ENDPOINTS.QUERY, params)
}

// 获取所有种母分娩记录
export function getAllEweLambing() {
  return readApi.get(API_CONFIG.ENDPOINTS.ALL)
}

// 获取种母分娩详情
export function getEweLambingDetail(id: number) {
  return readApi.get(`${API_CONFIG.ENDPOINTS.DETAIL}/${id}`)
}

// 新增种母分娩记录
export function addEweLambing(data: any) {
  return writeApi.post(API_CONFIG.ENDPOINTS.CREATE, data)
}

